<?php
/*
 * Don't have to edit anything in this file.
 * Just invoke this file regularily (for example: every second, every 3 seconds, every 1 minutes).
 * Invoking this file will make the items in database up-to-date.
 * For UNIX, this file should be invoked by crontab.
 */
require('includes/connect.inc.php');
require('includes/rss_fetch.inc');
require('includes/external_channel_lib.php');

header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header ("Cache-Control: no-cache, must-revalidate");
header ("Pragma: no-cache");

// get the least recently updated channel's id

$min = get_least_recently_updated_channel();
if(empty($min)) exit("No external channel");
echo "CHANNEL ID: " . $min['channel_id'] . " ";

$items = parsing_items($min['ext_link']);

// this flag is for check whether all sql commands are correct
$flag = true;

$sql = "LOCK TABLES externalfeed WRITE, item WRITE, channel WRITE";
$db->sql_query($sql);

$sql = "UPDATE externalfeed SET lastupdate = NOW() WHERE link = '" . $min['ext_link'] . "'";
$flag &= $db->sql_query($sql);

if(!empty($items)) {
	foreach($items as $item) {
		// Check whether this item is duplicated with the existing item in database
		if(!is_duplicate_item($min['channel_id'], $item['title'], $item['link'])) {

			//$item['description'] .= " <a href='" . $item['link'] . "'>read more...</a>";
				
			$sql = "INSERT INTO item(channelid, title, link, description, pubdate, author, isPublish, real_pubDate)
					VALUES (
					'" . $min['channel_id'] . "', 
					'" . $item['title'] . "', 
					'" . $item['link'] . "', 
					'" . $item['description'] . "', 
					'" . $item['pubdate'] . "', 
					'" . $item['author'] . "', 
					'1', 
					'" . $item['real_pubdate'] . "');";
			$flag &= $db->sql_query($sql);
			
//			echo $sql . '<br />';
		}
	}
}

$sql = "UNLOCK TABLES";
$db->sql_query($sql);

$db->sql_close();

// debug
echo $flag ? "SUCCEED" : "FAIL";
echo " " . date("H:i:s");
?>